package com.gitee.fsadmin.interceptor;

import com.gitee.fsadmin.common.exception.BizException;
import com.gitee.fsadmin.common.exception.ErrorCode;
import com.gitee.fsadmin.common.exception.ExceptionCode;
import com.gitee.fsadmin.common.resp.Result;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;
import org.noear.solon.validation.ValidatorException;

@Component(index = 0) //index 为顺序位（不加，则默认为0）
@Slf4j
public class AppRouterInterceptor implements RouterInterceptor {
    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
        try {
            chain.doIntercept(ctx, mainHandler);

            if (mainHandler == null) {
                ctx.render(Result.err("资源不存在"));
            }
        } catch (ValidatorException e) {
            ctx.render(Result.err(e.getMessage())); //e.getResult().getDescription()
        } catch (Throwable e) {
            Result result;
            if (e instanceof ExceptionCode) {
                ExceptionCode exceptionCode = (ExceptionCode) e;
                ErrorCode errorCode = exceptionCode.getCode();
                log.error("报错，code:{}, msg:{}", errorCode.getCode(), errorCode.getMsg(), e);
                result = Result.err(errorCode.getCode(), errorCode.getMsg());
            } else  if (e instanceof BizException || e instanceof IllegalArgumentException) {
                result = Result.err(e.getMessage());
            } else {
                log.error("未知错误，URI：{}", ctx.uri(), e);
                result = Result.err("服务器错误");
            }
            // 处理JSR-303错误
            /*if (e instanceof MethodArgumentNotValidException) {
                MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
                List<ObjectError> allErrors = exception.getBindingResult().getAllErrors();
                String msg = allErrors.stream()
                        .map(DefaultMessageSourceResolvable::getDefaultMessage)
                        .collect(Collectors.joining(", "));
                result = Result.err(msg);
            }*/
            ctx.render(result);
        }
    }
}
